package com.hundsun.cprs.yyt.web.action.trade;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.service.common.Constants;
import com.hundsun.cprs.yyt.service.trade.domain.EntrustAuditLog;
import com.hundsun.cprs.yyt.service.trade.domain.EntrustImportLog;
import com.hundsun.cprs.yyt.service.trade.domain.query.EntrustAuditLogQuery;
import com.hundsun.cprs.yyt.service.trade.domain.query.EntrustImportLogQuery;
import com.hundsun.cprs.yyt.service.trade.service.EntrustAuditLogService;
import com.hundsun.cprs.yyt.service.trade.service.EntrustImportLogService;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.util.ExportExcelUtil;
import com.hundsun.cprs.yyt.util.SequenceUtils;
import com.hundsun.cprs.yyt.util.excel.EasyExcelUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.util.ExportExcelWrapper;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import com.hundsun.cprs.yyt.web.vo.excel.EntrustAuditExcelVo;
import com.hundsun.cprs.yyt.web.vo.excel.EntrustImportExcelVo;
import com.hundsun.cprs.yyt.web.vo.excel.OrderInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author herong22384
 * @date 2019/8/13 14:21
 */
@RequestMapping("entrust/")
@Controller
public class BatchImportAction extends BaseAction {

    public static final String YYT_ENTRUST_IMPORT_LOCK = Constants.YYT_ENTRUST_IMPORT_LOCK;
    public static final String YYT_BATCH_AUDIT_LOCK = Constants.YYT_BATCH_AUDIT_LOCK;

    @Autowired
    private EntrustImportLogService logService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EntrustAuditLogService auditLogService;

    @RequestMapping(value = "batch/import-get")
    public String batchImport(@ModelAttribute("query") EntrustImportLogQuery query){
        if (query.getStartDate()==null){
            query.setStartDate(DateUtil.getBeginOfDay(new Date()));
        }
        if (query.getEndDate() == null){
            query.setEndDate(DateUtil.getEndOfDay(new Date()));
        }
        logService.queryByPage(query);
        return "trade/entrust/audit/batch_import";
    }

    @RequestMapping(value = "batch/import",method=RequestMethod.POST)
    public @ResponseBody
    String batchImport(@RequestParam("file") MultipartFile file){
        try{
            if (redisTemplate.hasKey(YYT_ENTRUST_IMPORT_LOCK)){
                JsonModel result = new JsonModel(JsonModel.RESULD_CODE_FAIL,"上次导入系统还未处理完成，请稍后再试");
                return JSON.toJSONString(result);
            }

            //设置全局锁，在本次导入操作完成时释放
            BoundValueOperations valueOperations = redisTemplate.boundValueOps(YYT_ENTRUST_IMPORT_LOCK);
            valueOperations.set(YYT_ENTRUST_IMPORT_LOCK,2L,TimeUnit.HOURS);

            List<EntrustImportExcelVo> uploadDatas = EasyExcelUtil.readExcel(file, EntrustImportExcelVo.class);
            List<EntrustImportLog> datas = new ArrayList<>();
            for( EntrustImportExcelVo temp : uploadDatas) {
                EntrustImportLog log = new EntrustImportLog();
                log.setAmount(temp.getAmmount());
                log.setFundAccount(temp.getFundAccount());
                log.setGoodsCode(temp.getGoodsCode());
                log.setOrderSn(temp.getOrderSn());
                log.setBuyPrice(temp.getBuyPrice());
                log.setStatus(0);
                datas.add(log);
                //每两万条批量插入一次
                if (datas.size() >= 20000){
                    logService.batchInsert(datas);
                    datas = new ArrayList<>();
                }
            }
            //生成批量导入流水记录
            logService.batchInsert(datas);
            //处理挂售单导入业务
            logService.handleBatchEntrust();

            Map<String,Object> importStatInfo = new HashMap<String,Object>();
            importStatInfo.put("total", uploadDatas.size());
            importStatInfo.put("uniqueTotal", uploadDatas.size());

            JsonModel result = new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"success",importStatInfo);
            return JSON.toJSONString(result);
        }catch (Exception e){
            redisTemplate.delete(YYT_ENTRUST_IMPORT_LOCK);
            JsonModel result = new JsonModel(JsonModel.RESULD_CODE_FAIL,"导入失败:"+e.getMessage());
            return JSON.toJSONString(result);
        }
    }

    @RequestMapping(value = "import/audit")
    public String importAudit(@ModelAttribute("query") EntrustAuditLogQuery query){
        if (query.getStartDate()==null){
            query.setStartDate(DateUtil.getBeginOfDay(new Date()));
        }
        if (query.getEndDate() == null){
            query.setEndDate(DateUtil.getEndOfDay(new Date()));
        }
        auditLogService.queryByPage(query);
        return "trade/entrust/audit/batch_audit";
    }

    @RequestMapping(value = "batch/audit_post",method=RequestMethod.POST)
    public @ResponseBody
    String batchAudit(@RequestParam("file") MultipartFile file){
        try{
            if (redisTemplate.hasKey(YYT_BATCH_AUDIT_LOCK)){
                JsonModel result = new JsonModel(JsonModel.RESULD_CODE_FAIL,"上次导入系统还未处理完成，请稍后再试");
                return JSON.toJSONString(result);
            }

            //设置全局锁，在本次导入操作完成时释放
            BoundValueOperations valueOperations = redisTemplate.boundValueOps(YYT_BATCH_AUDIT_LOCK);
            valueOperations.set(YYT_BATCH_AUDIT_LOCK,2L,TimeUnit.HOURS);

            List<EntrustAuditExcelVo> uploadDatas = EasyExcelUtil.readExcel(file, EntrustAuditExcelVo.class);
            Set<EntrustAuditLog> datas = new HashSet<>();
            for( EntrustAuditExcelVo temp : uploadDatas) {
                EntrustAuditLog log = new EntrustAuditLog();
                log.setAuditAmount(temp.getAuditAmount());
                log.setEntrustAmount(temp.getEntrustAmount());
                log.setFundAccount(temp.getFundAccount());
                log.setGoodsCode(temp.getGoodsCode());
                log.setStatus(0);
                datas.add(log);
            }

            //生成批量审核导入流水记录
            auditLogService.batchInsert(new ArrayList<>(datas));
            //处理挂售单批量审核业务
            auditLogService.handleBatchAudit();

            Map<String,Object> importStatInfo = new HashMap<String,Object>();
            importStatInfo.put("total", uploadDatas.size());
            importStatInfo.put("uniqueTotal", datas.size());

            JsonModel result = new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"success",importStatInfo);
            return JSON.toJSONString(result);
        }catch (Exception e){
            redisTemplate.delete(YYT_BATCH_AUDIT_LOCK);
            JsonModel result = new JsonModel(JsonModel.RESULD_CODE_FAIL,"导入失败:"+e.getMessage());
            return JSON.toJSONString(result);
        }
    }

    @Override
    protected void initBinder(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }
}
